//  loads ICRG data and reshapes; adds country codes

cd "~/Documents/econ/research/current/cognitive/estimation/data"

local icrgvars GS SC IP IC EC C MIP RIP LO ET DA BQ
#delimit ;
local icrglabs `"	"Government Stability" 
	"Socioeconomic Conditions" 
	"Investment Profile"	
	"Internal Conflict"
	"External Conflict"
	"Corruption"
	"Military in Politics"
	"Religious Tensions"
	"Law and Order"
	"Ethnic Tensions"
	"Democratic Accountability"
	"Bureaucracy Quality" "';
#delimit cr
	
local niv : word count `icrgvars'
forvalues i = 1/`niv' {
	local iv : word `i' of `icrgvars'
	local il : word `i' of `icrglabs'
	local is = char(64+`i') + "-`il'"  // Add letters
	di `"iv = `iv'; il = `il'; is = `is'"'

	import excel ICRG2021.xls, sheet("`is'") cellrange(A8) firstrow clear
	foreach var of varlist _all {
			  local label : variable label `var'
			  local new_name = lower(strtoname("`label'"))
			  rename `var' `new_name'
	}
	quietly destring _2007, replace  // why does only 2007 become a str variable?
	// splice Serbia & Montenegro (1984-2006: obs. 111) to Serbia series 
	// 	(2006-2012; obs. 112) by taking the difference between the 2 series  
	//		in 2006 and adding it to the Serbia & Montenegro series
	scalar srbwedge = _2006[111] - _2006[112]
	forvalues y = 2001/2005 {
		qui replace _`y' = _`y'[_n+1] + srbwedge in 111
	}
	forvalues y = 1984/2000 {
		qui replace _`y' = _`y'[_n+1] in 111   // in 2000, goes close to 0
	} 
	qui drop in 112  // drop Serbia and Montenegro

	quietly reshape long _, i(country) j(year)
	rename _ `iv'
	label variable `iv' "`il'"

	if (`i'==1) qui save ICRG, replace
	else {
		quietly merge 1:1 country year using ICRG
		drop _merge
		qui save ICRG, replace
	}
}

replace country = "Serbia" if (country=="Serbia *")
egen double PRI = rowtotal(`icrgvars'), missing
label variable PRI "Political Risk Index"
save ICRG, replace

import excel ICRGcountrycode.xlsx, firstrow clear
merge 1:m country using ICRG
*tab country if _merge==1
drop if _merge==1

drop _merge
order country countrycode year PRI `icrgvars'
sort countrycode year
saveold ICRG_panel, replace version(11)
